﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using Client.Entity;
using Client.Utils;
using YTE;
using SocketClientHelper = Client.Utils.SocketClientHelper;

namespace Client
{
    public partial class FrmMain : Form
    {
        //客户端端口
        private int port = 0;
        //客户端本地存放文件路径
        private string folderPath = string.Empty;
        //客户端站位名
        private string positionName = string.Empty;
        //客户端本地IP地址
        private string localIP = string.Empty;

        public FrmMain()
        {
            InitializeComponent();
        }
        
        SocketClientHelper socketClientHelper;

        private void LogCallBack(string msg)
        {
            this.Invoke(new Action(() =>
            {
                this.richTextBox1.Text += msg + "\r\n";
            }));
        }
        private void ReciveProgressCallBack(string fileName, int size, long length)
        {
            this.Invoke(new Action(() =>
            {
                this.label1.Text = $"接收:{fileName},{size}/{length}";
            }));
        }
        private void ReciveCallBack(SendType sendType, string msg)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (socketClientHelper == null) return;
            if (!socketClientHelper.IsConnect) return;

            string[] localEnd = socketClientHelper.GetSocket.LocalEndPoint.ToString().Split(':');
            localIP = localEnd[0];
            ClientMsgModel clientMsgModel = new ClientMsgModel()
            {
                IP = localIP,
                Status = comboBox_position.Text,
            };
            string jsonOjbect = Newtonsoft.Json.JsonConvert.SerializeObject(clientMsgModel);
            socketClientHelper.SendObject(jsonOjbect);

        }

        private void SendPositionName()
        {
            if (socketClientHelper == null) return;
            if (!socketClientHelper.IsConnect) return;

            string[] localEnd = socketClientHelper.GetSocket.LocalEndPoint.ToString().Split(':');
            localIP = localEnd[0];
            ClientMsgModel clientMsgModel = new ClientMsgModel()
            {
                IP = localIP,
                Status = comboBox_position.Text,
            };
            string jsonOjbect = Newtonsoft.Json.JsonConvert.SerializeObject(clientMsgModel);
            socketClientHelper.SendObject(jsonOjbect);
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            this.GetPositionInfo();
        }

        private void BtnStart_Click(object sender, EventArgs e)
        {
            try
            {
                if (!CheckIpAndFolderPath()) return;
                socketClientHelper = new SocketClientHelper(TxtIp.Text, port, folderPath)
                {
                    LogAction = LogCallBack,
                    ReciveProgressAction = ReciveProgressCallBack,
                    ReciveAction = ReciveCallBack
                };
                socketClientHelper.Start();
                
                this.SendPositionName();
            }
            catch (Exception exception)
            {
                LogHelper.Error(exception);
            }
           
        }

        #region [获取APP.config文件中站位信息]
        private void GetPositionInfo()
        {
            try
            {
                Dictionary<string, string> dicPosition = ConfigUtils.GetConfig();
                BindingSource bd = new BindingSource
                {
                    DataSource = dicPosition
                };
                comboBox_position.DataSource = bd;
                comboBox_position.DisplayMember = "Value";
                comboBox_position.ValueMember = "Key";
                comboBox_position.SelectedIndex = -1;
            }
            catch (Exception e)
            {
                LogHelper.Error(e);
            }

        }
        #endregion

        #region [刷新Label信息]
        private void RefLabel(Label lb,string msg)
        {
            lb.Invoke(new Action<string>(x =>
            {
                lb.Text = x;
            }), msg);
        }
        #endregion

        private bool CheckIpAndFolderPath()
        {
            if (string.IsNullOrEmpty(TxtIp.Text.Trim()))
            {
                MessageBox.Show(@"请先输入服务端IP地址");
                return false;
            }
            localIP = TxtIp.Text.Trim();

            if (TxtPort.Text.Trim().Length < 0)
            {
                MessageBox.Show(@"请先输入服务端的端口号");
                return false;
            }
            port = int.Parse(TxtPort.Text.Trim());

            if (string.IsNullOrEmpty(comboBox_position.Text))
            {
                MessageBox.Show(@"请先选择站位");
                return false;
            }

            if (string.IsNullOrEmpty(TxtFolderPath.Text))
            {
                MessageBox.Show(@"请先选择站位存放目录路径");
                return false;
            }

            positionName = comboBox_position.Text;
            folderPath = TxtFolderPath.Text.Trim();
            return true;
        }

        private void BtnSelectFolder_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog
            {
                Description = @"请选择文件存放路径",
            };
            DialogResult result = fbd.ShowDialog();
            if (result != DialogResult.OK) return;

            TxtFolderPath.Text = fbd.SelectedPath;
        }

        private void BtnClose_Click(object sender, EventArgs e)
        {
            socketClientHelper.GetSocket.Close();
        }

        #region[验证IP]
        /// <summary>
        /// 验证IP
        /// </summary>
        public static bool RegexIP(string str)
        {
            return Regex.IsMatch(str.Trim(), @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }
        #endregion
    }

}
